package com.utils.lib.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.annotation.DrawableRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.maning.updatelibrary.InstallUtils;
import com.utils.lib.BuildConfig;
import com.utils.lib.R;
import com.utils.lib.http.UConstant;
import com.utils.lib.http.UNewNetwork;
import com.utils.lib.model.UADModel;
import com.utils.lib.utilsview.UDialog;
import com.utils.lib.utilsview.UtilsPrivacyPolicy;

import java.io.File;

public abstract class UBaseSplashActivity extends UBaseActivity {
    public static final String TAG = "UBaseSplashActivity";
    public  FrameLayout container;
    public  ImageView img;
    public  TextView skip;
    public  UtilsPrivacyPolicy u_utils;
    public  UNewNetwork instance;

    public static final String SKIP_TEXT = "点击跳过 %d";
    public static final String APK_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AlmightyFlight/update.apk";

    /**
     * @return 启动页显示图片
     */
    protected abstract @DrawableRes
    int getImg();

    /**
     * 允许进入请求权限
     */
    protected abstract void initPermission();

    @Override
    protected int getResourceId() {
        return R.layout.activity_splash_u;
    }

    /**
     * 只用于初始化当前app需要实例化的内容  不适用当前页面初始化数据
     */
    protected abstract void initData();

    public void initUContent() {
    }

    @Override
    protected void initView() {
        initUContent();
        container = findViewById(R.id.v_fl_container);
        img = findViewById(R.id.v_iv_img);
        skip = findViewById(R.id.v_tv_skip);
        u_utils = findViewById(R.id.u_utils);
        u_utils.setAttribute(UConstant.APP_NAME, UConstant.LAYOUT_COLOR, UConstant.TEXT_COLOR, UConstant.APP_THEME_COLOR, UConstant.TEXT_LAYOUT_COLOR);
        Glide.with(UBaseSplashActivity.this).load(getImg()).into(img);
        initOnClick();
        initData();
        u_utils.setOnUtilsPrivacyPolicyListener(new UtilsPrivacyPolicy.OnUtilsPrivacyPolicyListener() {
            @Override
            public void onPermission() {//允许进入 进行操作
                if (Build.VERSION.SDK_INT >= getVERSION()) {
                    initPermission();
                } else {
                    initADType(1);
                }
            }
        });
    }

    public boolean isDownLoad = false;

    /**
     * 请求广告
     *
     * @param index 0 无广告 1 有广告
     */
    public void initADType(int index) {
        if (index == 0) {
            starMain(1);
        } else {
            instance = UNewNetwork.getInstance();
            instance.initAdHttp("1", new UNewNetwork.OnHttpListener() {
                @Override
                public void succeed(final UADModel o) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (null == o || null == o.getData()) {
                                starMain(404);
                                return;
                            }
                            int isStatus = o.getData().getIsStatus();
                            if (isStatus == 1) {
                               initNewAD();
                            } else if (isStatus == 2) {
                                isDownLoad = true;
                                //原生广告
                                Glide.with(UBaseSplashActivity.this).load(o.getData().getLitpic()).into(img);
                                img.setTag(o.getData().getLinkurl());
                                skip.setVisibility(View.VISIBLE);
                                container.setVisibility(View.GONE);
                                img.setVisibility(View.VISIBLE); // 广告展示后一定要把预设的开屏图片隐藏起来
                                new CountDownTimer(3000, 1000) {
                                    @SuppressLint("DefaultLocale")
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        skip.setText(String.format(SKIP_TEXT, millisUntilFinished / 1000));
                                    }

                                    @Override
                                    public void onFinish() {
                                        starMain(2);
                                    }
                                }.start();
                            } else {
                                starMain(3);
                            }
                        }
                    });
                }

                @Override
                public void error() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            starMain(404);
                        }
                    });
                }
            });
        }

    }

    /**
     * @return 新广告时 直接选true
     */
    public boolean getNew() {
        return false;
    }



    private void initOnClick() {
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isDownLoad) return;
                if (!TextUtils.isEmpty(v.getTag().toString())) {
                    InstallUtils.with(UBaseSplashActivity.this).setApkUrl(v.getTag().toString()).setApkPath(APK_SAVE_PATH)
                            .setCallBack(new InstallUtils.DownloadCallBack() {
                                @Override
                                public void onStart() {
                                    Toast.makeText(UBaseSplashActivity.this, "后台下载中...", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onComplete(String path) {
                                    InstallUtils.checkInstallPermission(UBaseSplashActivity.this, new InstallUtils.InstallPermissionCallBack() {
                                        @Override
                                        public void onGranted() {
                                            //去安装APK
                                            installAPK(APK_SAVE_PATH, UBaseSplashActivity.this);
                                        }

                                        @Override
                                        public void onDenied() {
                                        }
                                    });
                                }

                                @Override
                                public void onLoading(long total, long current) {
                                }

                                @Override
                                public void onFail(Exception e) {
                                }

                                @Override
                                public void cancle() {
                                }
                            }).startDownload();
                }
            }
        });
        skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                starMain(4);
            }
        });
    }

    /**
     * 跳转到主页
     *
     * @param i 当前跳转值
     */
    public abstract void starMain(int i);


    /**
     * 安装APK
     */
    public static void installAPK(String apkSavePath, FragmentActivity a) {
        File apkFile = new File(apkSavePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(a
                    , BuildConfig.APPLICATION_ID + ".fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        a.startActivity(intent);
    }

    public UDialog dialog;
    public boolean isTrue = true;

    public void showDialog() {
        if (null == dialog) {
            dialog = new UDialog(UBaseSplashActivity.this, "权限提示!",
                    "打开", "退出",
                    "此应用需要打开定位、存储权限，否则部分功能将无法正常使用，是否打开？", new UDialog.ClickListener() {
                @Override
                public void doConfirm() {
                    Intent intent = new Intent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                    startActivity(intent);
                    dialog.dismiss();
                    isTrue = true;
                }

                @Override
                public void doCancel() {
                    finish();
                }

                @Override
                public void doDismiss() {
                    isTrue = true;
                    initPermission();
                }
            });
        }
        dialog.show();
    }


    /**
     * @return 要控制的版本号
     */
    public int getVERSION() {
        return 23;
    }

    /**
     * @return 趣赢id
     */
    public String getQYID() {
        return UConstant.QYID;
    }

    public void initNewAD() {
    }
}
